package com.library.librarybackend.controller;

import com.library.librarybackend.domain.dto.AttachmentDownloadDTO;
import com.library.librarybackend.domain.vo.AttachmentVO;
import com.library.librarybackend.service.AttachmentService;
import com.library.librarybackend.service.OSSService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.jetbrains.annotations.NotNull;
import org.springframework.core.io.InputStreamResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

/**
 * @author 平
 * @description 附件控制类
 * @since 2025-09-21 21:59
 */
@Tag(name = "附件控制类")
@RestController
@RequiredArgsConstructor
@RequestMapping("/attachment")
public class AttachmentController {

    private final AttachmentService attachmentService;

    @Operation(summary = "下载附件")
    @PostMapping(value = "/download")
    public ResponseEntity<Resource> download(@RequestBody @Validated AttachmentDownloadDTO attachmentDownloadDTO) {
        // 查询附件
        AttachmentVO attachmentVO = attachmentService.queryByObjName(attachmentDownloadDTO.getObjName());
        // 下载 附件
        InputStream inputStream = attachmentService.download(attachmentDownloadDTO.getObjName());
        // 创建InputStreamResource
        InputStreamResource resource = new InputStreamResource(inputStream);

        HttpHeaders headers = getHeaders(attachmentDownloadDTO.getObjName());

        return ResponseEntity.ok()
                .headers(headers)
                .contentLength(attachmentVO.getSize())
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .body(resource);
    }

    @NotNull
    public static HttpHeaders getHeaders(String objName) {
        String[] split = objName.split(OSSService.SEPARATOR);
        split = split[split.length - 1].split(OSSService.DASHED);
        StringBuilder sb = new StringBuilder();
        for (int i = 1; i < split.length; i++) {
            if (i > 1) sb.append(OSSService.DASHED);
            sb.append(split[i]);
        }
        String filename = sb.toString();
        // 对文件名进行URL编码，确保在HTTP头中正确传输
        String encodedFilename = URLEncoder.encode(filename, StandardCharsets.UTF_8);
        // 设置响应头
        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + encodedFilename + "\"; filename*=UTF-8''" + encodedFilename);
        headers.add(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS, HttpHeaders.CONTENT_DISPOSITION);
        return headers;
    }


}
